<template>
  <div class="point-records-container">
    <div class="page-header">
      <h1>积分记录管理</h1>
    </div>

    <!-- 筛选条件区域 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" ref="filterFormRef">
        <!-- 第一行：时间范围 + 班级选择 -->
        <div class="filter-row">
          <!-- 时间范围选择 -->
          <el-form-item label="时间范围" prop="dateRange">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>

          <!-- 班级下拉菜单（仅管理员和教师可见） -->
          <el-form-item label="班级" prop="classId" v-if="showClassFilter">
            <el-select
              v-model="filterForm.classId"
              placeholder="请选择班级"
              clearable
            >
              <el-option
                v-for="cls in classList"
                :key="cls.id"
                :label="`${cls.grade}年级${cls.name}`"
                :value="cls.id"
              />
            </el-select>
          </el-form-item>
        </div>

        <!-- 第二行：学号 + 学生姓名 + 按钮 -->
        <div class="filter-row">
          <!-- 学号筛选 -->
          <el-form-item label="学号" prop="studentNumber" v-if="showClassFilter">
            <el-input
              v-model="filterForm.studentNumber"
              placeholder="请输入学号"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>

          <!-- 学生姓名筛选（部分匹配） -->
          <el-form-item label="学生姓名" prop="studentName" v-if="showClassFilter">
            <el-input
              v-model="filterForm.studentName"
              placeholder="请输入姓名"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>

          <!-- 搜索按钮 -->
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </div>

        <!-- 第三行：导出按钮 -->
        <div class="filter-row" v-if="showClassFilter">
          <el-form-item>
            <el-button type="default" style="background-color: #555; color: #fff;"
            @click="handleExport">
              <el-icon><Download /></el-icon>
              导出积分记录报表
            </el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-card>

    <!-- 积分记录列表 -->
    <el-card class="records-table" v-loading="tableLoading">
      <el-table
        :data="recordsList"
        border
        style="width: 100%"
      >
        <el-table-column
          prop="classInfo"
          label="年级班级"
          width="140"
        />
        <el-table-column
          prop="student_name"
          label="学生姓名"
          width="100"
        />
        <el-table-column
          prop="points_change"
          label="积分"
          width="80"
        >
          <template #default="scope">
            <span :style="{ color: scope.row.points_change > 0 ? '#10b981' : '#ef4444' }">
              {{ scope.row.points_change > 0 ? `+${scope.row.points_change}` : scope.row.points_change }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="reason"
          label="理由"
          min-width="180"
        />
        <el-table-column
          prop="teacher_name"
          label="操作老师"
          width="120"
        />
        <el-table-column
          prop="operated_at"
          label="操作时间"
          width="180"
          sortable
          sort-orders="descending"
        />
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50]"
          :pager-count="5"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageSizeChange"
          @current-change="handleCurrentPageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElForm } from 'element-plus';
import { listClasses, type ClassItem } from '../../api/classmgr';
import { exportPointRecords, getPointRecords, type PointRecordItem, type PointRecordsParams, type PointRecordsResponse } from '../../api/point';
import { useAuthStore } from '../../store/authStore';
import { Download } from '@element-plus/icons-vue';

// 状态管理
const tableLoading = ref(false);
const recordsList = ref<PointRecordItem[]>([]);
const classList = ref<ClassItem[]>([]);
const filterFormRef = ref<InstanceType<typeof ElForm>>();

// 用户权限判断（仅管理员和教师显示班级筛选）
const authStore = useAuthStore();
const userRole = computed(() => authStore.user?.role);
const showClassFilter = computed(() => {
  return userRole.value === 'admin' || userRole.value === 'teacher';
});

// 筛选表单数据（所有可选参数初始化为undefined）
const filterForm = reactive<{
  dateRange?: [string, string];  // 时间范围可选
  classId?: number;             // 班级可选
  studentNumber?: string;       // 学号可选
  studentName?: string;         // 姓名可选
}>({
  // 初始值全部为undefined，符合接口可选性要求
});


// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 初始化页面
onMounted(async () => {
  // 获取班级列表（仅管理员和教师）
  if (showClassFilter.value) {
    try {
      const res = await listClasses();
      if (res.code === 200) {
        classList.value = res.content;
      }
    } catch (error: any) {
      ElMessage.error(error.message || '获取班级列表失败');
    }
  }

  // 默认加载第一页数据
  await fetchPointRecords();
});

// 构造查询参数（严格匹配接口的可选性）
const buildQueryParams = (): PointRecordsParams => {
  const params: PointRecordsParams = {
    start: (pagination.currentPage - 1) * pagination.pageSize,
    limit: pagination.pageSize
  };

  // 仅在有值时添加可选参数，避免传递空字符串
  if (filterForm.dateRange?.[0]) params.start_time = filterForm.dateRange[0];
  if (filterForm.dateRange?.[1]) params.end_time = filterForm.dateRange[1];
  if (filterForm.classId !== undefined) params.class_id = filterForm.classId;
  if (filterForm.studentName) params.student_name = filterForm.studentName;
  if (filterForm.studentNumber) params.student_number = filterForm.studentNumber;

  return params;
};

// 获取积分记录列表
const fetchPointRecords = async () => {
  try {
    tableLoading.value = true;
    const params = buildQueryParams();
    const res: PointRecordsResponse = await getPointRecords(params);
    
    if (res.code === 200) {
      // 处理年级班级显示格式
      recordsList.value = res.content.records.map(record => ({
        ...record,
        classInfo: `${record.class_grade}年级${record.class_name}`
      }));
      pagination.total = res.content.total;
    } else {
      ElMessage.error(res.msg || '获取积分记录失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取积分记录异常');
  } finally {
    tableLoading.value = false;
  }
};

// 搜索按钮点击
const handleSearch = async () => {
  pagination.currentPage = 1; // 重置到第一页
  await fetchPointRecords();
};

// 重置筛选条件（恢复为undefined）
const resetFilter = () => {
  filterForm.dateRange = undefined;
  filterForm.classId = undefined;
  filterForm.studentNumber = undefined;
  filterForm.studentName = undefined;
  pagination.currentPage = 1;
  fetchPointRecords();
};

// 分页大小变化
const handlePageSizeChange = async (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1; // 重置到第一页
  await fetchPointRecords();
};

// 页码变化
const handleCurrentPageChange = async (page: number) => {
  pagination.currentPage = page;
  await fetchPointRecords();
};

// 导出积分记录处理函数
const handleExport = async () => {
  // 教师权限下必须选择一个班级才能导出
  if (userRole.value === 'teacher' && !filterForm.classId) {
    ElMessage.error('必须选择班级后才能进行导出操作。');
    return;
  }

  try {
    // 构建导出参数（复用查询参数逻辑并适配接口要求）
    const exportParams = {
      class_id: filterForm.classId,
      // 注意：页面现有筛选条件中没有group_id和student_id，这里保持可选
      group_id: undefined,
      student_id: undefined,
      start_time: filterForm.dateRange?.[0],
      end_time: filterForm.dateRange?.[1],
    };

    // 调用导出接口
    const blob = await exportPointRecords(exportParams);
    
    // 处理二进制文件流
    const url = window.URL.createObjectURL(new Blob([blob]));
    const a = document.createElement('a');
    a.href = url;
    // 设置文件名（可根据实际需求调整）
    a.download = `积分记录_${new Date().toLocaleDateString()}.xlsx`;
    document.body.appendChild(a);
    a.click();
    
    // 清理资源
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
    
    ElMessage.success('导出成功');
  } catch (error: any) {
    ElMessage.error(error.message || '导出失败');
  }
};
</script>

<style scoped>
.point-records-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 20px;
  color: var(--el-text-color-primary);
}

/* 筛选区域布局调整 */
.filter-card {
  padding: 15px 20px;
  margin-bottom: 8px;
}

/* 每行筛选条件容器 */
.filter-row {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 15px;
  flex-wrap: wrap; /* 小屏幕下自动换行 */
}

/* 最后一行去除底部间距 */
.filter-row:last-child {
  margin-bottom: 0;
}

/* 表单项目间距优化 */
.el-form-item {
  margin-bottom: 0 !important; /* 覆盖element默认样式 */
}

/* 输入框宽度统一调整 */
.el-date-picker, .el-select, .el-input {
  width: 240px;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .filter-row {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .el-date-picker, .el-select, .el-input {
    width: 100%;
  }
}

.records-table {
  padding: 15px;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

/* 积分颜色样式 */
::deep .el-table .cell {
  white-space: normal;
  word-break: break-word;
}

.filter-container {
  display: flex;
  flex-wrap: wrap;  /* 允许筛选条件换行，避免拥挤 */
  gap: 15px;
}
</style>